<template>
  <el-row :gutter="20" class="mgb20">
    <el-col :span="24">
      <el-card shadow="hover" :body-style="{ height: '400px' }">
        <div class="card-header">
          <p class="card-header-title">AI助手</p>
          <p class="card-header-desc">与AI助手进行对话，获取帮助和建议</p>
        </div>
        <div class="chat-container">
          <div ref="chatMessagesRef" class="chat-messages">
            <div
              v-for="(msg, index) in chatMessages"
              :key="index"
              class="chat-message"
              :class="{ 'user-message': msg.isUser, 'ai-message': !msg.isUser }"
            >
              <div class="message-avatar">
                <el-icon v-if="msg.isUser"><User /></el-icon>
                <el-icon v-else><ChatDotRound /></el-icon>
              </div>
              <div class="message-content" v-html="formatMessage(msg.content)"></div>
            </div>
          </div>
          <div class="chat-input">
            <el-input
              v-model="chatInput"
              placeholder="请输入您的问题..."
              :rows="3"
              type="textarea"
              resize="none"
              @keyup.enter.ctrl="sendMessage"
            />
            <el-button
              type="primary"
              :disabled="!chatInput.trim() || isLoading"
              @click="sendMessage"
            >
              <span v-if="!isLoading">发送</span>
              <span v-else>处理中</span>
              <el-icon v-if="!isLoading" class="el-icon--right"><Position /></el-icon>
              <el-icon v-else class="el-icon--right"><Loading /></el-icon>
            </el-button>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
  // AI 聊天模块组件，提取自 Dashboard.vue
  import { ref, nextTick, onMounted } from 'vue'
  import { ChatDotRound, User, Position, Loading } from '@element-plus/icons-vue'

  const chatInput = ref('')
  const chatMessages = ref([{ content: '您好，我是AI助手，有什么可以帮助您的吗？', isUser: false }])
  const chatMessagesRef = ref<HTMLElement | null>(null)
  const isLoading = ref(false)

  // 发送消息
  const sendMessage = async () => {
    if (!chatInput.value.trim() || isLoading.value) return
    chatMessages.value.push({ content: chatInput.value, isUser: true })
    const userMessage = chatInput.value
    chatInput.value = ''
    await nextTick()
    scrollToBottom()
    isLoading.value = true
    const tempMessageIndex = chatMessages.value.length
    chatMessages.value.push({ content: '正在思考中...', isUser: false })
    try {
      const messages = chatMessages.value.slice(0, -1).map(msg => ({
        role: msg.isUser ? 'user' : 'assistant',
        content: msg.content,
      }))
      messages.push({ role: 'user', content: userMessage })
      const param = { messages }
      const response = await fetch('/api/ai/chatWithStore', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(param),
      })
      if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
      const reader = response.body?.getReader()
      if (!reader) throw new Error('无法获取响应流')
      chatMessages.value[tempMessageIndex].content = ''
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        const text = new TextDecoder().decode(value)
        chatMessages.value[tempMessageIndex].content += text
        scrollToBottom()
      }
    } catch (error) {
      console.error('调用AI接口出错:', error)
      chatMessages.value[tempMessageIndex].content = '抱歉，发生了一些错误，请稍后再试。'
    } finally {
      isLoading.value = false
      scrollToBottom()
    }
  }

  // 滚动到底部
  const scrollToBottom = () => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  }

  // 格式化消息内容，去除多余的引号
  const formatMessage = (content: string) => {
    if (!content) return ''
    let result = content
    result = result.replace(/""+([^"]*)""+/g, '$1')
    result = result.replace(/""/g, '')
    result = result.replace(/" "/g, ' ')
    result = result.replace(/" /g, ' ')
    result = result.replace(/ "/g, ' ')
    result = result.replace(/\\n/g, '<br>')
    return result
  }

  onMounted(() => {
    scrollToBottom()
  })
</script>

<style scoped>
  /* 聊天框样式优化 */
  .el-row.mgb20 {
    margin-bottom: 24px;
  }
  .el-card {
    border-radius: 14px;
    box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.06);
    border: none;
  }
  .card-header {
    padding-left: 10px;
    margin-bottom: 16px;
  }
  .card-header-title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 2px;
    color: #222;
  }
  .card-header-desc {
    font-size: 14px;
    color: #888;
  }
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 320px;
    background: #fafbfc;
    border-radius: 10px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    padding: 12px 0 0 0;
  }
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 0 18px 10px 18px;
    margin-bottom: 0;
    background: transparent;
    border-radius: 10px 10px 0 0;
    scrollbar-width: thin;
    scrollbar-color: #e1e1e1 #fafbfc;
  }
  .chat-messages::-webkit-scrollbar {
    width: 6px;
  }
  .chat-messages::-webkit-scrollbar-thumb {
    background: #e1e1e1;
    border-radius: 6px;
  }
  .chat-message {
    display: flex;
    margin-bottom: 18px;
    align-items: flex-start;
  }
  .message-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    color: white;
    font-size: 20px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
  }
  .user-message .message-avatar {
    background: linear-gradient(135deg, #409eff 60%, #66b1ff 100%);
  }
  .ai-message .message-avatar {
    background: linear-gradient(135deg, #67c23a 60%, #95d475 100%);
  }
  .message-content {
    background: #fff;
    padding: 10px 18px;
    border-radius: 18px 18px 18px 4px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
    max-width: 70%;
    word-break: break-word;
    font-size: 15px;
    color: #333;
    line-height: 1.7;
    transition: background 0.2s;
  }
  .user-message .message-content {
    background: #e8f4ff;
    border-radius: 18px 18px 4px 18px;
    margin-left: auto;
  }
  .ai-message .message-content {
    background: #f4fbe8;
    border-radius: 18px 18px 18px 4px;
    margin-right: auto;
  }
  .chat-input {
    display: flex;
    align-items: flex-end;
    gap: 10px;
    padding: 12px 18px 12px 18px;
    background: #fff;
    border-radius: 0 0 10px 10px;
    width: 100%;
    box-sizing: border-box;
    border-top: 1px solid #f0f0f0;
  }
  .chat-input .el-textarea {
    flex: 1;
    max-width: calc(100% - 90px);
    font-size: 15px;
  }
  .chat-input .el-button {
    margin: 0;
    padding: 0 24px;
    height: 100%;
    min-height: 40px;
    font-size: 16px;
    border-radius: 20px;
    box-shadow: 0 2px 8px 0 rgba(64, 158, 255, 0.1);
    background: linear-gradient(90deg, #409eff 60%, #66b1ff 100%);
    color: #fff;
    border: none;
    transition:
      background 0.2s,
      box-shadow 0.2s,
      opacity 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
  }
  .chat-input .el-button:active {
    background: linear-gradient(90deg, #337ecc 60%, #409eff 100%);
    box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.18);
  }
  .chat-input .el-button:hover:not(:disabled) {
    background: linear-gradient(90deg, #66b1ff 60%, #409eff 100%);
    opacity: 0.95;
  }
  .chat-input .el-button:disabled {
    background: #e0e6ed;
    color: #bfcbd9;
    opacity: 0.7;
    box-shadow: none;
    cursor: not-allowed;
  }
  .chat-input .el-icon--right {
    margin-left: 4px;
    font-size: 18px;
  }
  @media (max-width: 900px) {
    .el-card {
      padding: 0;
    }
    .chat-container {
      height: 220px;
    }
    .chat-messages {
      padding: 0 8px 6px 8px;
    }
    .chat-input {
      padding: 8px 8px 8px 8px;
    }
  }
</style>
